package com.sky.ok.okex.websocket.base;

import com.sky.ok.okex.websocket.client.WebSocketService;
import com.sky.ok.okex.websocket.client.WebSocketV3;
import com.sky.ok.okex.websocket.client.WebSocketV3API;
import com.sky.ok.okex.websocket.client.WebSoketClient;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.util.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

import static com.sky.ok.okex.common.OKV3Const.FUTURE_BTC_INDEX;
import static com.sky.ok.okex.common.OKV3Const.FUTURE_EOS_INDEX;
import static com.sky.ok.okex.utils.utils.uncompress;

/**
 * @author 余心乐sky
 * @create 2019-01-30 15:40
 **/
public class WebSocketListenerV3  extends WebSocketListener  {

    private static final Logger log = LoggerFactory.getLogger("WebSocketListenerV3.class");
    private WebSocketService service ;

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        System.out.println(text);
    }

    @Override
    public void onClosing(WebSocket webSocket, int code, String reason) {
        log.warn("正在关闭websocket");
    }

    @Override
    public void onClosed(WebSocket webSocket, int code, String reason) {
        System.out.println("关闭");
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
        //连接失败的时候抛出异常
        log.error("WebSocket连接失败!!!");
        //数据库写入失败也会到这！！
        //需要重启websocket了
        WebSoketClient client = WebSocketV3.getInstance();
        System.out.printf( client.getSubscribChannel().toString());
        //set转数组
        String[] subscribe = client.getSubscribChannel().toArray(new String[client.getSubscribChannel().size()]);
        //重置websocket状态，使之新建新的对象
        WebSocketV3.setClient(null);
        //启动新的websocket！！！
        log.error("正在尝试重新建立webSocket连接");
        WebSocketV3API webSocketV3API =new WebSocketV3API();
        webSocketV3API.subscribe(subscribe);

    }

    @Override
    public void onMessage(WebSocket webSocket, ByteString bytes) {
        String st = uncompress(bytes.toByteArray());
        if(!"pong".equals(st)){
            try {
                service.onReceive(st);
            } catch(Exception e){
                log.error("数据格式不正确，写入数据库失败！！！");
            }


        }
    }

    public WebSocketService getService() {
        return service;
    }

    public void setService(WebSocketService service) {
        this.service = service;
    }

}
